package com.example.horizonserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.horizonserver.common.exception.EditPasswordException;
import com.example.horizonserver.common.exception.LoginFailedException;
import com.example.horizonserver.common.exception.UserEecption;
import com.example.horizonserver.common.exception.UserSaveException;
import com.example.horizonserver.common.result.PageResult;
import com.example.horizonserver.mapper.UserMapper;
import com.example.horizonserver.pojo.DTO.EditPasswordDTO;
import com.example.horizonserver.pojo.DTO.UserDTO;
import com.example.horizonserver.pojo.DTO.UserLoginDTO;
import com.example.horizonserver.pojo.DTO.UserPageQueryDTO;
import com.example.horizonserver.pojo.entity.User;
import com.example.horizonserver.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {


    private final UserMapper userMapper;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUsername, username);
        User user = userMapper.selectOne(lqw);
        //2、处理各种异常情况（用户名不存在、密码不对）
        if (user == null) {
            //账号不存在
            throw new LoginFailedException("用户名不存在");
        }
        //密码比对
        // TODO 对明文密码进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new LoginFailedException("密码错误");
        }
        //3、返回实体对象
        return user;
    }

    /**
     * 新增用户信息
     * @param userDTO
     */
    @Override
    @CacheEvict(cacheNames = "userPageCache", allEntries = true)
    public void save(UserDTO userDTO) {
        //验证username唯一性
        String username = userDTO.getUsername();
        if(username == null)
        {
            throw new UserSaveException("用户名不能为空");
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, username);
        User user = userMapper.selectOne(lqw);
        if(user != null)
        {
            throw new UserSaveException("用户名已存在");
        }
        User newUser = new User();
        //实体类转化
        //对象属性拷贝 BeanUtils.copyProperties
        BeanUtils.copyProperties(userDTO, newUser);
        //设置密码 默认123456,并进行md5加密存储
        newUser.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        userMapper.insert(newUser);
    }

    /**
     * 批量删除员工
     *
     * @param ids
     */
    @Override
    @CacheEvict(cacheNames = "userPageCache", allEntries = true)
    public void deleteBatch(List<Integer> ids) {
        //根据员工id集合动态批量删除员工数据
        List<User> users = userMapper.selectByIds(ids);
        if(users.size() != ids.size())
        {
            throw new UserEecption("存在不存在的用户");
        }
        userMapper.deleteByIds(ids);
    }
    /**
     * 条件分页查询员工数据
     *
     * @param userPageQueryDTO
     * @return
     */
    @Override
    @Cacheable(
            value = "userPageCache",
            key = "'page:' + #userPageQueryDTO.page + ':' + #userPageQueryDTO.pageSize",
            condition = "#userPageQueryDTO.pageSize == 5 " +
                    "&& (#userPageQueryDTO.name == null || #userPageQueryDTO.name == '') " +
                    "&& (#userPageQueryDTO.sex == null || #userPageQueryDTO.sex == '') " +
                    "&& #userPageQueryDTO.role == null || #userPageQueryDTO.role == ''"
    )
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        //判断前端是否传page和pageSize参数
        if(userPageQueryDTO.getPage() == null|| userPageQueryDTO.getPageSize() == null)
        {
            throw new UserEecption("未指定页数和每页数据数");
        }
        //判断sex跟role是否合乎规矩
        if(!Objects.equals(userPageQueryDTO.getSex(), "") && userPageQueryDTO.getSex() != null && !(userPageQueryDTO.getSex().equals("男") || userPageQueryDTO.getSex().equals("女")))
        {
            throw new UserEecption("用户性别不合法");
        }
        if(userPageQueryDTO.getRole() != null && !(userPageQueryDTO.getRole() == 1 || userPageQueryDTO.getRole() == 2))
        {
            throw new UserEecption("用户职责不合法");
        }
        // 构建分页参数
        Page<User> page = new Page<>(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        // 构建查询条件
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        // 员工姓名模糊查询
        lqw.like(StringUtils.isNotBlank(userPageQueryDTO.getName()), User::getName, userPageQueryDTO.getName());
        // 员工性别精确查询
        lqw.eq(StringUtils.isNotBlank(userPageQueryDTO.getSex()), User::getSex, userPageQueryDTO.getSex());
        // 员工职责精确查询
        lqw.eq(userPageQueryDTO.getRole() != null, User::getRole, userPageQueryDTO.getRole());
        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(page, lqw);
        log.info("查库");
        // 封装返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(userPage.getTotal());
        pageResult.setRecords(userPage.getRecords());
        return pageResult;
    }

    /**
     * 根据id查询用户 用作修改回显
     *
     * @param id
     * @return
     */
    @Override
    public User getById(Integer id) {
        User user = userMapper.selectById(id);
        if(user == null)
        {
            throw new UserEecption("用户不存在");
        }
        return user;
    }

    /**
     * 修改用户信息
     *
     * @param userDTO
     */
    @Override
    @CacheEvict(cacheNames = "userPageCache", allEntries = true)
    public void update(UserDTO userDTO) {
        if(userMapper.selectById(userDTO.getId())==null)
        {
            throw new UserEecption("用户不存在");
        }
        if(userDTO.getUsername() == null)
        {
            throw new UserEecption("用户名不能为空");
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userMapper.updateById(user);
    }
    /**
     * 修改密码
     *判断异常情况  旧密码输错了  新密码跟旧密码一样了
     * @param editPasswordDTO
     */
    @Override
    @CacheEvict(cacheNames = "userPageCache", allEntries = true)
    public void editPassword(EditPasswordDTO editPasswordDTO) {
        User user = userMapper.selectById(editPasswordDTO.getId());
        String oldPassword = DigestUtils.md5DigestAsHex(editPasswordDTO.getOldPassword().getBytes());
        if(!oldPassword.equals(user.getPassword()))
        {
            throw new EditPasswordException("旧密码输入错误");
        }
        String newPassword = DigestUtils.md5DigestAsHex(editPasswordDTO.getNewPassword().getBytes());
        if(newPassword.equals(user.getPassword()))
        {
            throw new EditPasswordException("新密码不能与旧密码相同");
        }
        user.setPassword(newPassword);
        userMapper.updateById(user);
    }

}
